<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>每日清单</title>
    <link rel="stylesheet" href="./css/daylist.css">
</head>
<body>
    <div class="wrapper">
        <h2>每日清单</h2>
        <p></p>
        <ul class="tasks">
            <li>加载清单...</li>
        </ul>
        <form class="add-tasks">
            <input type="text" name="task" placeholder="" required>
            <input type="submit" value="+ 添加">
        </form>
    </div>
    <script>
        const tasksList = document.querySelector('.tasks')
        const addTasks = document.querySelector('.add-tasks')
        const tasks = JSON.parse(localStorage.getItem('tasks')) || []

        function addTask(e) {
            e.preventDefault(); // 清除表单默认提交
            const text = this.querySelector('[name=task]').value
            console.log(text);
            const task = {
                text,
                done: false
            }
            tasks.push(task)
            localStorage.setItem('tasks',JSON.stringify(tasks))
            showTask(tasks, tasksList)
            this.reset() // 表单重置功能
        }

        function showTask(tasks=[], tasksList) {
            tasksList.innerHTML = tasks.map((task,i) => {
                return `
                <li>
                    <input type="checkbox" data-index=${i} ${task.done?'checked':''} id="task${i}" />
                    <label for="task${i}">${task.text}</label>
                </li>
                `
            }).join('')
        }

        function toggleDone(e) {
            const el = e.target
            if(!el.matches('input')) return;
            const index = el.dataset.index
            tasks[index].done = !tasks[index].done
            localStorage.setItem('tasks',JSON.stringify(tasks))

        }


        addTasks.addEventListener('submit',addTask)

        showTask(tasks, tasksList)

        tasksList.addEventListener('click',toggleDone)

    </script>
</body>
</html>